package com.leyou.goods.service;

import com.leyou.goods.utils.ThreadUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.Context;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.PrintWriter;
import java.util.Map;

/**
 * @Description:
 * @author: Mr_Sun
 * @Date: 2018/9/20
 * @Time: 19:56
 */
@Service
public class GoodsHtmlService {
    @Autowired
    private TemplateEngine engine;

    @Autowired
    private GoodsService goodsService;
    PrintWriter printWriter = null;
    public  void creatHtml(Long id) {
        try {
            //初始化上下文
            Context context = new Context();

            //获取数据模型
            Map<String, Object> map = this.goodsService.loadData(id);
            //设置数据模型
            context.setVariables(map);
            //初始化流
             printWriter = new PrintWriter("D:\\nginx-1.12.2\\nginx-1.12.2\\html\\item\\"+id+".html");

            this.engine.process("item", context,printWriter);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } finally {
            if (printWriter != null) {
                printWriter.close();
            }

        }
    }
    /**
     * 新建线程处理页面静态化
     * @param spuId
     */
    public void asyncExcute(Long spuId) {
        ThreadUtils.execute(() -> creatHtml(spuId));
        /*ThreadUtils.execute(new Runnable() {
            @Override
            public void run() {
                createHtml(spuId);
            }
        });*/
    }

    public void deleteHtml(Long id) {
        File file = new File("D:\\nginx-1.12.2\\nginx-1.12.2\\html\\item\\" + id + ".html");
        file.deleteOnExit();
    }
}
